import os
import time

import requests
from flask import Flask, request, jsonify
import gradio as gr

import tempfile
import os

# 设置自定义临时目录
custom_temp_dir = './custom_temp_dir'

# 确保目录存在
if not os.path.exists(custom_temp_dir):
    os.makedirs(custom_temp_dir)

# 设置全局临时目录
tempfile.tempdir = custom_temp_dir

# Gradio接口，录音并上传到Flask服务器
def record_audio(audio):
    # Gradio会传递一个临时文件路径
    if audio is not None:
        with open(audio, 'rb') as f:
            files = {'file': f}
            response = requests.post('http://127.0.0.1:5000/upload_audio', files=files)
            return response.json()
    else:
        return {"error": "No audio recorded"}

# temp_directory = './custom_temp_dir'
# Gradio界面
gr_interface = gr.Interface(
    fn=record_audio,
    inputs=gr.Audio(sources=["microphone", 'upload'], type="filepath"),
    outputs="json",
    title="Audio Recorder",
    description="Record audio and upload to server",
    # temp_dir=temp_directory
)

# 启动Flask和Gradio应用
if __name__ == "__main__":
    # Gradio独立运行
    gr_interface.launch()

    # 启动Flask应用
    # app.run(debug=True, port=5000)
